<template>
  <a-modal
    :width="1000"
    v-model:visible="visible"
    :title="title"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleClose"
    :bodyStyle="{ padding: '0 10px 10px' }"
  >
    <div class="list-title">{{ t('字段列表') }}</div>
    <a-row type="flex" align="middle" :gutter="12" style="margin: 15px 0">
      <a-col flex="auto" class="text-right">{{ t('调用接口：') }}</a-col>
      <a-col flex="75%">
        <a-input v-model:value="apiConfigInfo.path" disabled />
      </a-col>
      <a-col flex="auto">
        <a-button key="submit" type="primary" @click="viewInterfaceInfo">{{
          t('查看接口信息')
        }}</a-button>
      </a-col>
    </a-row>
    <a-table
      :dataSource="apiConfigInfo.outputParams"
      :columns="apiColumns"
      :pagination="false"
      :scroll="{ y: '400px' }"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'show'">
          {{ t('是否在弹层列表显示') }}
          <a-checkbox v-model:checked="checkedAll" @change="handleChecked" />
        </template>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'name'">
          <a-input
            v-model:value="record.name"
            :placeholder="t('请填写字段名')"
            :disabled="disabled"
          />
        </template>
        <template v-else-if="column.key === 'component'">
          <a-select
            v-model:value="record.bindField"
            style="width: 100%"
            :placeholder="t('请选择填充组件')"
            @change="(value) => selectBindField(value, record)"
            allowClear
            :disabled="disabled"
          >
            <a-select-option :value="val.bindField" v-for="(val, idx) in selectedList" :key="idx">
              {{ val.label }}
            </a-select-option>
          </a-select>
        </template>
        <template v-else-if="column.key === 'tableTitle'">
          <a-input v-model:value="record.tableTitle" :placeholder="t('请填写表头名称')" />
        </template>
        <template v-else-if="column.key === 'show'">
          <a-checkbox v-model:checked="record.show" />
        </template>
        <template v-else-if="column.key === 'width'">
          <a-input
            v-model:value="record.width"
            :disabled="!record.show"
            :placeholder="t('请填写列表宽度')"
          />
        </template>
        <template v-else-if="column.key === 'action'">
          <DeleteTwoTone two-tone-color="#ff8080" @click="deleteParamas(index)" />
        </template>
      </template>
    </a-table>
    <a-button type="dashed" block @click="addOutPutParamas" :disabled="disabled">
      <PlusOutlined />
      {{ t('新增') }}
    </a-button>
  </a-modal>
  <InterfaceInfoModal @register="registerModal" />
</template>

<script lang="ts" setup>
  import { watch, ref, reactive } from 'vue';
  import { ColumnProps } from 'ant-design-vue/lib/table/Column';
  import { PlusOutlined, DeleteTwoTone } from '@ant-design/icons-vue';
  import InterfaceInfoModal from './InterfaceInfoModal.vue';
  import { useModal } from '/@/components/Modal';
  import { message } from 'ant-design-vue';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const props = defineProps({
    apiAssoDia: { type: Boolean },
    apiConfig: {
      type: Object as PropType<any>,
    },
    selectedList: { type: Array as any },
    type: { type: String },
    disabled: { type: Boolean, default: () => false },
  });
  const emit = defineEmits(['update:apiAssoDia', 'update:apiConfig']);
  const visible = ref<boolean>(props.apiAssoDia);

  const [registerModal, { openModal }] = useModal();

  const apiConfigInfo = ref();
  const apiColumns = ref<ColumnProps[]>([]);
  const title = ref<string>('');
  const checkedAll = ref<boolean>(false);
  const multiplePopupColumns = reactive<ColumnProps[]>([
    {
      title: '#',
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 50,
    },
    {
      title: t('接口返回参数字段名'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: 200,
    },
    {
      title: t('表头名称'),
      dataIndex: 'tableTitle',
      key: 'tableTitle',
      align: 'center',
      width: 150,
    },
    {
      title: t('是否在弹层中显示'),
      dataIndex: 'show',
      key: 'show',
      align: 'center',
      width: 200,
    },
    {
      title: t('列表宽度'),
      dataIndex: 'width',
      key: 'width',
      align: 'center',
      width: 100,
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      width: 50,
    },
  ]);

  const associatePopupColumns = reactive<ColumnProps[]>([
    {
      title: '#',
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 50,
    },
    {
      title: t('接口返回参数字段名'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: 200,
    },
    {
      title: t('填充组件'),
      dataIndex: 'component',
      key: 'component',
      align: 'center',
    },
    {
      title: t('表头名称'),
      dataIndex: 'tableTitle',
      key: 'tableTitle',
      align: 'center',
      width: 200,
    },
    {
      title: t('是否在弹层列表显示'),
      dataIndex: 'show',
      key: 'show',
      align: 'center',
      width: 200,
    },
    {
      title: t('列表宽度'),
      dataIndex: 'width',
      key: 'width',
      align: 'center',
      width: 100,
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      width: 50,
    },
  ]);

  const associateSelectColumns = reactive<ColumnProps[]>([
    {
      title: '#',
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 50,
    },
    {
      title: t('接口返回参数字段名'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: 200,
    },
    {
      title: t('填充组件'),
      dataIndex: 'component',
      key: 'component',
      align: 'center',
    },
    {
      title: t('填充组件绑定字段'),
      dataIndex: 'bindField',
      key: 'bindField',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      width: 50,
    },
  ]);
  const preloadColumns = reactive<ColumnProps[]>([
    {
      title: '#',
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 50,
    },
    {
      title: t('接口返回参数字段名'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('表头名称'),
      dataIndex: 'tableTitle',
      key: 'tableTitle',
      align: 'center',
    },
  ]);
  watch(
    () => props.type,
    (val) => {
      switch (val) {
        case 'associate-popup':
          apiColumns.value = associatePopupColumns;
          title.value = t('联想数据配置-API');
          break;
        case 'multiple-popup':
          apiColumns.value = multiplePopupColumns;
          title.value = t('多选数据配置-API');
          break;
        case 'associate-select':
          apiColumns.value = associateSelectColumns;
          title.value = t('联想数据配置-API');
          break;
        case 'preload-title':
          apiColumns.value = preloadColumns;
          title.value = t('表头配置-API');
          break;
      }
    },
    { immediate: true },
  );

  watch(
    () => props.apiConfig,
    (val) => {
      apiConfigInfo.value = cloneDeep(val);
    },
    {
      deep: true,
      immediate: true,
    },
  );

  watch(
    () => apiConfigInfo.value,
    (val) => {
      checkedAll.value = val?.outputParams?.every((item: any) => {
        return item.show;
      });
    },
    {
      deep: true,
      immediate: true,
    },
  );

  function selectBindField(value, record) {
    if (!value || !isNaN(value)) {
      message.error(t('请先选择该组件的绑定表及绑定字段'));
      record.bindField = null;
    }
  }
  function handleClose() {
    emit('update:apiAssoDia', false);
  }
  function handleChecked(e) {
    apiConfigInfo.value.outputParams.map((item: any) => (item.show = e.target.checked));
  }

  function handleSubmit() {
    const bindFieldArr = <any>[];
    apiConfigInfo.value.outputParams?.map((item: any) => {
      if (item.bindField) {
        bindFieldArr.push(item.bindField);
      }
    });
    if (new Set(bindFieldArr).size !== bindFieldArr.length) {
      message.error(t('组件存在重复绑定,请更改'));
      return;
    }
    emit('update:apiConfig', apiConfigInfo.value);
    emit('update:apiAssoDia', false);
  }

  const viewInterfaceInfo = () => {
    openModal(true, {
      script: props.apiConfig.script,
    });
  };

  const addOutPutParamas = () => {
    if (!apiConfigInfo.value.outputParams) {
      apiConfigInfo.value.outputParams = [];
    }
    let configObj = {};
    switch (props.type) {
      case 'associate-popup':
        configObj = {
          name: '',
          tableTitle: '',
          bindField: '',
          show: true,
          width: 150,
        };
        break;
      case 'multiple-popup':
        configObj = {
          name: '',
          tableTitle: '',
          show: true,
          width: 150,
        };
        break;
      case 'associate-select':
        configObj = {
          name: '',
          bindField: '',
        };
        break;
    }
    apiConfigInfo.value.outputParams.push(configObj);
  };
  const deleteParamas = (index) => {
    if (props.disabled) return;
    apiConfigInfo.value.outputParams.splice(index, 1);
  };
</script>

<style lang="less" scoped>
  .list-title {
    margin: 10px 0 5px;
    font-size: 14px;
    line-height: 16px;
    padding-left: 6px;
    border-left: 6px solid #5e95ff;
  }
</style>
